package com.kfm.login.interceptor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kfm.login.domain.SysUser;
import com.kfm.login.service.SysUserService;
import com.kfm.login.util.AesUtil;
import com.kfm.login.util.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class RememberMeInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SysUserService sysUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
        if ("post".equalsIgnoreCase(method)){
            return true;
        }
        Cookie[] cookies = request.getCookies();
        if (cookies != null){
            String token = null;
            SysUser sysUser = null;
            for (Cookie cookie : cookies){
                if (Constant.TOKEN_KEY.equals(cookie.getName())){
                    token = cookie.getValue();
                }
                if (Constant.REMEMBER_ME.equals(cookie.getName())){
                    String value = cookie.getValue();
                    // kdSq7udGrjzkAZmS/z68wA==--RK/PqhTkQZjNzw3CFjuFcg==
                    String[] split = value.split("--");
                    String username = split[0];
                    String password = split[1];
                    // 数据库查询
                    QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
                    queryWrapper.select("id", "username", "phone", "password", "email", "state");
                    queryWrapper.eq("username", AesUtil.AES_CBC_Decrypt_String(username));
                    queryWrapper.eq("password", password);

                    sysUser = sysUserService.getOne(queryWrapper);
                }
            }

            if (sysUser != null){
                // 登录成功
                // 存 redis
                redisTemplate.opsForValue().set(Constant.USER_PRE + token, sysUser);
                // 重定向到 index
                response.sendRedirect("/index");
                return false;
            }
        }
        return true;
    }
}
